package com.vincent.sciinfo.service.impl;

import com.vincent.sciinfo.mapper.LoginCountMapper;
import com.vincent.sciinfo.pojo.LoginCount;
import com.vincent.sciinfo.pojo.User;
import com.vincent.sciinfo.service.LoginCountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class LoginCountServiceImpl implements LoginCountService {

    @Autowired
    private LoginCountMapper loginCountMapper;

    @Override
    @Transactional
    public int checkUserCountNum(User user) {
        int code = 1;
        try {
            LoginCount loginCountSelect = new LoginCount();
            loginCountSelect.setUserid(user.getUserId());
            //根据这个userId查到对应的信息 包括用户名与登录次数
            loginCountSelect = loginCountMapper.selectOne(loginCountSelect);

            //如果第一次登录 就置为1
            if (loginCountSelect == null) {
                LoginCount loginCountInsert = new LoginCount();
                loginCountInsert.setUserid(user.getUserId());
                loginCountMapper.insertOne(loginCountInsert, 1);
            } else {
                //否则 根据这个信息对象 更改为+1
                loginCountMapper.updateOne(loginCountSelect, loginCountSelect.getLogincount() + 1);
            }
        } catch (Exception e) {
            code = 0;
            return code;
        }
        return code;
    }

    @Override
    public List<LoginCount> showLoginCountData() {
        List<LoginCount> list = loginCountMapper.selectAll();
        return list;
    }

}
